package com.whosly.api.autoconfigure.context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;

public class SpringContextAwareHolder implements ApplicationContextAware, ISpringContextAware {
    private static final Logger log = LoggerFactory.getLogger(SpringContextAwareHolder.class);

    private static ApplicationContext context;

    public SpringContextAwareHolder() {
        //.
    }

    @Override
    public void setApplicationContext(@Nullable ApplicationContext context) throws BeansException {
        SpringContextAwareHolder.context = context;
    }

    @Override
    public <T> T getBean(Class<T> clazz) {
        return clazz == null ? null : getContext().getBean(clazz);
    }

    @Override
    public <T> T getBean(String beanName, Class<T> clazz) {
        if (null != beanName && !"".equals(beanName.trim())) {
            return clazz == null ? null : getContext().getBean(beanName, clazz);
        }

        return null;
    }

    public static <T> T get(Class<T> clazz) {
        return clazz == null ? null : getContext().getBean(clazz);
    }

    public static <T> T get(String beanName, Class<T> clazz) {
        if (null != beanName && !"".equals(beanName.trim())) {
            return clazz == null ? null : getContext().getBean(beanName, clazz);
        }

        return null;
    }

    public static ApplicationContext getContext() {
        return context == null ? null : context;
    }

}
